<template>
	<view class="img" style="position: relative;overflow: hidden;" @contextmenu.prevent="openContextMenu"
		v-if="!errorFlag&&item">

		<view class="item" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave" @mousemove="handleTouchMove"
			v-show="item.streamUrl" :id="'videoContainer' + item.index">
			<!-- https://ext.dcloud.net.cn/plugin?id=8843 插件地址 -->
			<yingbing-video ref="video" class="img " :flvConfig="{hasAudio:false,hasVideo: true}" :objectFit="objectFit" :enableLongpressPlaybackRate="false"
				:enableDoubleToggle="false" :src="item.streamUrl" :playShow="false" :timeShow="false"
				:volumeShow="false" :settingShow="false" :fullscreenShow="false" :controls="false" :progressShow="false"
				:barrageShow="false" :autoplay="true" @playing="playing" @captureFinish="onCaptureFinish"
				@loadstart="loadstart" @canplay="canplay" :style="divStyle" :muted="muted" @error="error">
			</yingbing-video>
			<view class="itemName " v-show="item.name">
				{{item.name}} {{item.ChuangKou}}
			</view>

			<view class="chaImg" @click="chaHaoClick" v-show="show">
				<image src="/static/img/jiankong/43.png" class="img" mode=""></image>
			</view>
			<view class="picture" v-if="picture">
				<view class="text">录像中</view>
			</view>
			<view class="caoZuo u-f-item" v-show="show&&type==1" id="targetView">
				<view class="caoZuoItem u-f-justify" @click="KaiFaZhong">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/13.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">报警</view>
				</view>
				<view class="caoZuoItem u-f-justify" @click="KaiFaZhong">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/19.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">回放</view>
				</view>
				<view class="caoZuoItem u-f-justify" :class="{caoZuoItem1:item.DuiJiang}" @click="DuiJiangClick">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/17.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">对讲</view>
				</view>
				<view class="caoZuoItem u-f-justify" @click="TongHuaClick">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/16.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">通话</view>
				</view>
				<view class="caoZuoItem u-f-justify" :class="{caoZuoItem1:!muted}" @click="muted = !muted">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/15.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">音频</view>
				</view>
				<view class="caoZuoItem u-f-justify" @click="zhuaTuClick">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/14.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">抓图</view>
				</view>
				<view class="caoZuoItem u-f-justify" :class="{caoZuoItem1:picture}" @click="pictureClick">
					<view class="icon u-f-justify">
						<image src="/static/img/jiankong/18.png" class="img" mode="widthFix"></image>
					</view>
					<view class="text" v-if="!small">录像</view>
				</view>
			</view>

		</view>
		<view class="img u-f-justify " style="background-color: #121212;" v-if="!item.streamUrl">
			<view>
				<image src="/static/img/jiankong/8.png" style="width: 72px;" mode="widthFix"></image>
			</view>
		</view>
		<view class="img waiting u-f-justify u-f-column" v-show="waitingFalg&&item.streamUrl">
			<view class="icon">
				<image src="/static/img/jiankong/5.png" class="img" mode="widthFix"></image>
			</view>
			<view class="text">
				加载中，请稍等
			</view>
		</view>

		<!-- 右键弹窗 -->
		<view v-if="showContextMenu" class="context-menu u-f-column u-f-item"
			:style="{ top: `${menuY}px`, left: `${menuX}px` }">
			<div class="menu-item u-f-item u-f-jsb" @click="handleMenuItemClick(1)">
				<view>关闭视频</view>
				<!-- <view class="icon u-f-justify">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view> -->
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="handleMenuItemClick(2)">
				<view>关闭所有视频</view>
				<!-- 	<view class="icon u-f-justify">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view> -->
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="handleMenuItemClick(3)" v-if="type==1">
				<view>连续抓图</view>
				<!-- <view class="icon u-f-justify">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view> -->
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="liuMaClick(1)" v-if="type==1">
				<view>主码流</view>
				<view class="icon u-f-justify" v-if="liuma==1">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view>
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="liuMaClick(2)" v-if="type==1">
				<view>子码流</view>
				<view class="icon u-f-justify" v-if="liuma==2">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view>
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="objectFit = 'cover'">
				<view>适应窗口显示</view>
				<view class="icon u-f-justify" v-if="objectFit=='cover'">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view>
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="objectFit = 'contain'">
				<view>原始分辨率显示</view>
				<view class="icon u-f-justify" v-if="objectFit=='contain'">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view>
			</div>
			<div class="menu-item u-f-item u-f-jsb" @click="handleMenuItemClick(8)" v-if="type==1">
				<view>全屏</view>
				<!-- <view class="icon u-f-justify">
					<image src="/static/img/jiankong/71.png" class="img" mode="widthFix"></image>
				</view> -->
			</div>
		</view>
		<el-dialog v-model="dialogVisible" title="提示" width="500" :align-center="true" :before-close="handleClose">
			<span>窗口{{item.index + 1}}录像完成，是否保存？</span>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="stopRecording">
						保存
					</el-button>
				</div>
			</template>
		</el-dialog>
	</view>
</template>

<script>
	import {
		ElMessage
	} from 'element-plus'
	import {
		lkrequest,
		lkfetch,
	} from '../../../js/lk/request.js'
	export default {
		props: {
			item: {},
			type: {
				default: 1 // 1 是实时监控页面
			}
		},
		data() {
			return {
				player: null,
				waitingFalg: false,
				show: false,
				showContextMenu: false, // 控制弹窗显示
				menuX: 0, // 弹窗的 X 坐标
				menuY: 0, // 弹窗的 Y 坐标
				scale: 1, // 当前缩放比例
				minScale: 1, // 最小缩放比例
				maxScale: 5, // 最大缩放比例
				scaleStep: 0.1, // 每次滚轮的缩放步长
				mouseX: 0, // 鼠标在 div 中的 X 坐标
				mouseY: 0, // 鼠标在 div 中的 Y 坐标
				mouseX1: 0, // 鼠标在 div 中的 X 坐标
				mouseY1: 0, // 鼠标在 div 中的 Y 坐标
				muted: true, //是否禁音
				picture: false,
				DanZhua: false,
				objectFit: 'contain',
				errorFlag: false,
				windows: {}, // 窗口状态管理
				timers: {}, // 定时器存储
				isPlaying: false,
				liuma: 1,
				mediaRecorder: null,
				recordedChunks: [],
				dialogVisible: false,
				cuid: "",
				small: false
			}
		},
		mounted() {
			uni.$off('callSucceed')
			uni.$on('callSucceed', res => {
				uni.hideLoading()
				let user = uni.getStorageSync('user')
				uni.navigateTo({
					url: '/pages/index/video?priv_room_cuid=' + this.cuid + '&huiyiname=' + user.user
						.nickName + '&ismic=1&iscam=1'
				})
			})
			setTimeout(() => {
				const container = document.querySelector(`#videoContainer${this.item.index}`);
				if (container) {
					container.addEventListener("wheel", this.handleWheel, {
						passive: false
					});
				}
			}, 1000)

		},
		computed: {
			divStyle() {
				return {
					transform: `scale(${this.scale})`,
					transformOrigin: `${this.mouseX}px ${this.mouseY}px`, // 以鼠标位置为中心缩放
					transition: "transform 0.1s ease", // 平滑过渡
				};
			},
		},
		methods: {
			waiting() {
				// 视频需要加载 停下来

				this.waitingFalg = true
			},
			playing() {
				//视频停下来加载完成 开始播放
				this.waitingFalg = false
			},
			handleMouseEnter(event) {
				this.show = true
				setTimeout(() => {
					this.getWidth()
				}, 100)
			},
			handleMouseLeave() {
				this.show = false
			},
			// 打开右键菜单
			openContextMenu(event) {
				if (this.item.streamUrl) {
					this.showContextMenu = true; // 显示弹窗
					this.menuX = event.clientX; // 获取鼠标 X 坐标
					this.menuY = event.clientY; // 获取鼠标 Y 坐标

					// 监听页面点击事件，关闭弹窗
					document.addEventListener('click', this.closeContextMenu);
				}

			},
			// 关闭右键菜单
			closeContextMenu() {
				this.showContextMenu = false; // 隐藏弹窗
				document.removeEventListener('click', this.closeContextMenu); // 移除事件监听
			},
			// 处理菜单项点击
			handleMenuItemClick(option) {
				this.closeContextMenu(); // 关闭弹窗
				this.$emit('handleMenuItemClick', {
					index: option,
					item: this.item
				})
			},
			liuMaClick(index) {
				if (this.liuma != index) {
					this.$emit('liuMaClick', {
						item: this.item,
						sta: index
					})
					this.liuma = index
				}
				this.closeContextMenu(); // 关闭弹窗
			},
			chaHaoClick() {
				this.$emit('chaHaoClick', this.item)
			},
			onCaptureFinish(e) {
				if (this.DanZhua) {
					this.DanZhua = false
					this.$emit('onCaptureFinish', {
						list: [e],
						name: this.item.name,
						id: this.item.id,
						device_code: this.item.device_code
					})
				}
			},
			// 单次抓图
			zhuaTuClick() {
				this.DanZhua = true
				this.$refs.video.capture()
			},
			// 监听触摸移动事件，更新触摸点位置
			handleTouchMove(event) {
				const touch = event.touches[0]; // 获取第一个触摸点
				this.updateMousePosition(touch.clientX, touch.clientY);

			},
			// 监听滚轮事件，调整缩放比例
			handleWheel(event) {
				event.preventDefault(); // 阻止默认的滚轮行为
				if (event.deltaY > 0) {
					// 向上滚动，放大
					this.mouseX = this.mouseX1
					this.mouseY = this.mouseY1
					this.scale = Math.max(this.scale - this.scaleStep, this.minScale);
				} else {
					// 向下滚动，缩小
					this.mouseX = this.mouseX1
					this.mouseY = this.mouseY1
					this.scale = Math.min(this.scale + this.scaleStep, this.maxScale);
				}

			},
			// 更新鼠标位置
			updateMousePosition(clientX, clientY) {
				// 使用 uni.createSelectorQuery() 获取元素的位置信息
				uni
					.createSelectorQuery()
					.in(this)
					.select(".item")
					.boundingClientRect((rect) => {
						if (rect) {
							this.mouseX1 = clientX - rect.left; // 计算鼠标相对于 div 的 X 坐标
							this.mouseY1 = clientY - rect.top; // 计算鼠标相对于 div 的 Y 坐标
						}
					})
					.exec();
			},
			loadstart(e) {
				this.waitingFalg = true
			},
			canplay(e) {
				this.waitingFalg = false
			},
			KaiFaZhong() {
				ElMessage({
					message: '开发中...',
					type: 'warning',
				})
			},
			error() {

			},
			DuiJiangClick() {
				this.$emit('DuiJiangClick', this.item.index)
			},
			pictureClick() {
				if (!this.picture) {
					this.startRecording()
				} else {
					this.dialogVisible = true
					this.picture = false
				}
			},
			startRecording() {
				const videoEl = this.getInnerVideoElement();
				if (!videoEl) {
					console.error('找不到 video 元素');
					return;
				}
				const stream = videoEl.captureStream();
				this.recordedChunks = [];
				this.mediaRecorder = new MediaRecorder(stream, {
					mimeType: 'video/webm;codecs=vp8,opus',
				});
				this.mediaRecorder.ondataavailable = (event) => {
					if (event.data.size > 0) {
						this.recordedChunks.push(event.data);
					}
				};

				this.mediaRecorder.onstop = this.uploadRecording;
				this.mediaRecorder.start();
				this.picture = true
			},

			stopRecording() {
				if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
					this.mediaRecorder.stop();
				}
			},

			uploadRecording() {
				const blob = new Blob(this.recordedChunks, {
					type: 'video/webm'
				});
				const formData = new FormData();
				formData.append('file', blob, 'recorded_video.webm');
				this.$emit('picturerecording', {
					item: this.item,
					formData
				})
				lkfetch('/system/file/upload', formData, 'POST').then(res => {
					let fileId = res.data.fileId
					this.http('/resource/add', {
						deviceCode: this.item.device_code,
						channelCode: this.item.id,
						type: 1,
						fileId,
						fileIds: null,
					}, 'POST').then(res => {
						ElMessage({
							message: '保存录像成功',
							type: 'success',
							plain: true,
						})
						this.dialogVisible = false
					})
				})
			},

			getInnerVideoElement() {
				// 假设你的组件内部包裹了原生 <video>，尝试通过 ref 拿 DOM
				const comp = this.$refs.video;
				const video = comp?.$el?.querySelector('video');
				return video;
			},
			TongHuaClick() {
				// 关闭对讲音频
				if (this.item.DuiJiang) {
					this.$emit('DuiJiangClick', this.item.index)
				}
				this.muted = false
				uni.hideLoading()
				loginMgr.get_self_room_info().then(res => {
					loginMgr.select_usr_join_mr(res.cuid, '', res.ctrl_pwd, '', []).then(ress => {

						uni.hideLoading()
						if (ress.result == 0) {
							let ser = uni.getStorageSync('meetingService')
							let user = uni.getStorageSync('user').user
							this.cuid = res.cuid
							zjsdk3.make_call_now(ser.meetingIp, ser.port, res.cuid, res.ctrl_pwd, user
								.nickName)
							setTimeout(() => {
								zjsdk3.ags_invite_ipc([this.item.id])
							}, 2000)
						} else {
							if (ress.code == 7094) {
								uni.showToast({
									title: "当前会议室正在使用，请更换会议室",
									icon: "none"
								})
								return
							} else {
								uni.showToast({
									title: ress.reason,
									icon: "none"
								})
								return
							}
						}

					})
				})
			},
			getWidth() {
				uni.createSelectorQuery()
					.select('#targetView')
					.boundingClientRect(res => {
						if (res) {
							if (res.width < 400) {
								this.small = true
							} else {
								this.small = false
							}
						}
					})
					.exec();
			}
		}
	}
</script>
<style scoped>
	.img {
		width: 100%;
		height: 100%;
	}
</style>
<style scoped lang="scss">
	.item {
		position: relative;
		width: 100%;
		height: 100%;
		overflow: hidden;

		.itemName {
			position: absolute;
			top: 0;
			left: 0;
			padding: 4px 10px;
			background: rgba(0, 0, 0, 0.50);
			border-radius: 0 0 6px 0;
			font-size: 14px;
			font-family: Source Han Sans CN, Source Han Sans CN-400;
			font-weight: 400;
			text-align: LEFT;
			color: #ffffff;
		}

		.chaImg {
			position: absolute;
			top: 20px;
			right: 20px;
			width: 40px;
			height: 40px;
			z-index: 9;
		}

		.caoZuo {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 52px;
			background: rgba(0, 0, 0, 0.70);
			overflow: hidden;

			.caoZuoItem {
				height: 52px;
				padding: 0 10px;

				.icon {
					width: 24px;
				}

				.text {
					font-size: 12px;
					font-family: Microsoft YaHei, Microsoft YaHei-400;
					font-weight: 400;
					text-align: LEFT;
					color: #ffffff;
					margin-left: 3px;
					white-space: nowrap;
				}
			}

			.caoZuoItem1 {
				background: #165fff;
			}

		}
	}

	.waiting {
		position: absolute;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.50);

		.icon {
			width: 52px;
		}
	}

	.context-menu {
		position: fixed;
		/* 固定定位 */
		background: #1e1e1e;
		border: 1px solid #383838;
		border-radius: 6px;
		box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.25);
		z-index: 1000;

		/* 确保弹窗在最上层 */
		.menu-item {
			width: 131px;
			height: 36px;
			font-size: 14px;
			padding: 0 5px;

			.icon {
				width: 18px;
			}
		}

		.menu-item:hover {
			background-color: #165fff;
		}
	}

	.picture {
		width: calc(100% - 8px);
		height: calc(100% - 8px);
		position: absolute;
		border: 4px solid #FF4A50;
		top: 0;
		left: 0;

		.text {
			position: absolute;
			font-size: 42px;
			font-family: Microsoft YaHei, Microsoft YaHei-700;
			font-weight: 700;
			text-align: LEFT;
			color: #d82525;
			right: 60px;
			top: 20px;
		}
	}
</style>